/**
 * 
 */
package os.filesystem.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Property configurations.
 * 
 * @author Raghav Sidhanti
 * @since Mar 6, 2012 5:02:59 PM
 * 
 */
public class FSProperties {

	public static final String FILESYSTEM_NAME = "fs.name";
	public static final String DISK_LOCATION = "fs.disk.location";
	public static final String FILE_HIERARCHY_SEPERATOR = "fs.file.hseperator";
	public static final String FILE_ROOT = "fs.file.root";
	public static final String USER_SYSTEM = "fs.user.system";
	public static final String USER_LOGIN = "fs.user.login";
	public static final String USER_PROMPT = "fs.user.prompt";

	private static Properties props;
	private static Map<String, String> map;

	static {
		flush();
	}
	
	public static void flush(){
		props = new Properties();
		try {
			InputStream in = Object.class.getResourceAsStream("/filesystem.properties");
			props.load(in);
			map = new HashMap<String, String>();
		} catch (FileNotFoundException e) {
			System.err.println("filesystem.properties not found in classpath.");
		} catch (IOException e) {
			System.err.println("Unable to read filesystem.properties.");
		}
	}

	public static String getProperty(String key) {
		if(!map.containsKey(key)){
			map.put(key, replacePlaceholders(props.getProperty(key)));
		}
		return map.get(key);
	}

	static String replacePlaceholders(String str) {
		String PLACEHOLDER_PATTERN = "\\{(.*?)\\}";
		if (str != null) {
			Pattern pattern = Pattern.compile(PLACEHOLDER_PATTERN);
			Matcher matcher = pattern.matcher(str);
			while (matcher.find()) {
				String match = matcher.group().trim();
				String key = match.replace("{", "").replace("}", "");
				str = str.replace(match, getProperty(key));
			}
		}else{
			str = "null";
		}
		return str;
	}
}
